package dao;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import model.lectureRoom.Building;
import model.lectureRoom.LectureRoom;
import model.reservation.lectureRoom.Reservation;

import parsers.CommonMethods;
import parsers.reservation.ReservationLRParser;

public class ReservationLRDAO 
{
	private static Map<String, Reservation> reservationCP = new HashMap<String, Reservation>();
	
	private static String currentDate = util.Utilities.getDateTime();
	
	private static String file = makeFileName("resCP");
	
	private long startTime;
	
	@SuppressWarnings("unchecked")
	public ReservationLRDAO()
	{
		startTime();
		System.out.print("Initialising ReservationLRDAO->Reservation: ");
		if( (new File(file)).exists() )
		{
			System.out.print("(find serialized file " + file + ") ");
			reservationCP = (Map<String, Reservation>) util.Utilities.deserialize(file);
		}
		else
		{
			initReservationLRSchedule();
		}
		System.out.println(countTime() + " ms");
	}
	
	private static String makeFileName(String name)
	{
		return Linker.path + ReservationLRDAO.class.getName() + name + currentDate + ".jsr";
	}
	
	public static void serialize()
	{
		if( !(new File(file)).exists() )
		{
			util.Utilities.serialize(reservationCP, file);
		}
	}
	
	private void initReservationLRSchedule()
	{
		Iterator<Building> buildings = LectureRoomDAO.getBuildingsWithLectureRoomsCP().values().iterator();
		while(buildings.hasNext())
		{
			Building building = buildings.next();
			ArrayList<LectureRoom> lectureRooms = building.getLectureRooms();
			
			for (int i = 0; i < lectureRooms.size(); i++)
			{
				Reservation reservation = new Reservation(lectureRooms.get(i).getName(), lectureRooms.get(i).getCapacity(), lectureRooms.get(i).getType(), lectureRooms.get(i).getUnit());
				reservation.setId(lectureRooms.get(i).getId());
				reservation.setLink(CommonMethods.parseLink(lectureRooms.get(i).getLink()) + "&pTyp=R");
				
				try
				{
					ReservationLRParser lrp = new ReservationLRParser(reservation);
					lrp.parse();
					reservationCP.put(reservation.getId(), reservation);
				} 
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	public static Map<String, Reservation> getReservationCP()
	{
		return reservationCP;
	}

	private void startTime()
	{
		startTime = System.currentTimeMillis();
	}
	
	private long countTime()
	{
		return System.currentTimeMillis() - startTime;
	}
}